<script setup lang="ts">
// 爆款神器 数据分析
import DataChart from "~/contentScripts/views/sycm/market_monitor/popular_artifact/dataChart.vue";

const props = defineProps({
  dataSource: {
    type: Array,
    default: () => [],
  },
  title: {
    type: String,
    default: () => '店铺'
  }
});
let first = ref(true);
const maxPrice = ref(0);
const priceSplit = ref<any[]>([]);
const disabledIndexes = ref([]);
const calcMaxPrice = () => {
  // 计算最大客单价
  let max = 0;
  props.dataSource.map((item: any) => {
    if (max < parseFloat(item.customerUnitPrice)) {
      max = parseFloat(item.customerUnitPrice);
    }
  })
  maxPrice.value = max;
}
const defaults = ref<any[]>([]);
const numbers = ref<any>({});
onMounted(() => {
  calcMaxPrice();
})
watch(() => props.dataSource, () => {
  // first.value = true;
  calcMaxPrice();
}, {deep: true});
const calcNumberData = (prices) => {
  let numberData: any = {};
  for (let i = 1; i < prices.length; i++) {
    numberData[i] = 0;
    props.dataSource.map((item: any) => {
      if (parseFloat(item.customerUnitPrice) > parseFloat(prices[i - 1]) && parseFloat(item.customerUnitPrice) <= parseFloat(prices[i])) {
        numberData[i] += 1;
      }
    })
  }
  numbers.value = numberData;
}
let handleUpdate = false;
const calcNumbers = (prices, retry = 0) => {
  handleUpdate = true;
  prices = prices.filter((item) => typeof item !== 'undefined');
  let numberData: any = {};
  for (let i = 1; i < prices.length; i++) {
    numberData[i] = 0;
    props.dataSource.map((item: any) => {
      if (parseFloat(item.customerUnitPrice) > parseFloat(prices[i - 1]) && parseFloat(item.customerUnitPrice) <= parseFloat(prices[i])) {
        numberData[i] += 1;
      }
    })
  }

  if (first.value) {
    for (const numberDataKey in numberData) {
      if (numberData[numberDataKey] == 0) {
        // delete numberData[numberDataKey];
        delete prices[numberDataKey];
      }
    }
  }
  if (first.value) {
    // prices=prices.filter((item)=>item);
    let length = 0;
    for (const i in prices) {
      if (typeof prices[i] === 'number') {
        length++;
      }
    }
    // 如果区间小于8 从间隔最大的区间拆分 补满8个区间
    if (length < 9 && retry < 2) {
      let maxStep = 0;
      let maxIndex = 0;
      for (const numbersKey in numberData) {
        if (numberData[numbersKey] > maxStep) {
          maxStep = numberData[numbersKey];
          maxIndex = parseInt(numbersKey);
        }
      }
      let start = parseFloat(prices[maxIndex - 1]);
      let end = parseFloat(prices[maxIndex]);
      for (let i = start; i < end; i += 2) {
        prices.push(parseFloat((start + i).toFixed(2)));
      }
      // 从新对priceSplit排序
      prices.sort((a: any, b: any) => a - b);
      calcNumbers(prices, retry + 1);
    } else if (length >= 9) {
      // 从中取出最小的8个区间
      // while (length >= 9) {
      let minStep = 9999999999;
      let minIndex = 0;
      for (const numbersKey in numberData) {
        if (numberData[numbersKey] < minStep && typeof prices[parseInt(numbersKey)] !== 'undefined' && prices.length - 1 !== parseInt(numbersKey)) {
          minStep = numberData[numbersKey];
          minIndex = parseInt(numbersKey);
        }
      }
      length--;
      delete prices[minIndex];
      delete numberData[minIndex];
      let newPrice: any[] = [];
      for (const pricesKey in prices) {
        if (typeof prices[pricesKey] !== 'undefined') {
          newPrice.push(prices[pricesKey]);
        }
      }
      // console.log(newPrice.length, newPrice);
      if (newPrice.length === 9) {
        first.value = false;
        calcNumberData(newPrice);
        priceSplit.value = newPrice;
        defaults.value = [...newPrice].sort((a, b) => a - b);
        nextTick(() => {
          handleUpdate = false;
        })
      } else {
        calcNumbers(newPrice, retry + 1);
      }
    } else {
      first.value = false;
      priceSplit.value = prices;
      numbers.value = numberData;
      defaults.value = [...prices].sort((a, b) => a - b);
      nextTick(() => {
        handleUpdate = false;
      })
    }
  } else {
    first.value = false;
    numbers.value = numberData;
    priceSplit.value = prices;
    nextTick(() => {
      handleUpdate = false;
    })
  }
}
watch(() => priceSplit.value, (prices) => {
  if (!handleUpdate) {
    calcNumbers(prices);
  }
}, {deep: true})
watch(() => maxPrice.value, (val) => {
  first.value = true;
  defaults.value = [];
  calcNumbers([0, val]);
})
</script>

<template>
  <a-row type="flex" style="padding-top: 5px;">
    <a-col>
      客单价区间设置：
    </a-col>
    <a-col flex="1">
      <price-range :max="maxPrice" v-model:value="priceSplit" :defaults="defaults" :max-split="9"/>
    </a-col>
  </a-row>
  <a-row type="flex" style="margin-top: 20px;">
    <a-col>
      客单价区间选择：
    </a-col>
    <a-col flex="1">
      <a-row type="flex" :gutter="10">
        <template v-for="(price,index) in priceSplit">
          <template v-if="index>0">
            <a-col span="3">
              <div class="price-range-item" :class="{
                active:!disabledIndexes.includes(index)
              }"
                   @click="()=>{
                 if(disabledIndexes.includes(index)){
                   delete disabledIndexes[disabledIndexes.indexOf(index)]
                 }else {
                   disabledIndexes.push(index)
                 }
               }"
              >
                <div>{{ priceSplit[index - 1] }} ~ {{ priceSplit[index] }}元</div>
                <div>{{ title }} {{ numbers[index] || 0 }}</div>
              </div>
            </a-col>
          </template>
        </template>
      </a-row>
    </a-col>
  </a-row>
  <a-divider/>
  <data-chart :data-source="dataSource" :disabledIndexes="disabledIndexes" :price-range="priceSplit"/>
</template>

<style lang="less" scoped>
.price-range-item {
  border: solid #eee 2px;
  border-radius: 5px;
  font-size: 14px;
  padding: 5px 10px;
  cursor: pointer;
  margin-bottom: 10px;

  &.active {
    border: #1890ff solid 2px;
  }
}
</style>
